import React from "react";
import { z } from "zod";
import { useFieldArray, useForm } from "react-hook-form";
import { Button } from "@/components/custom/button";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/custom/password-input";
import CryptoJS from "crypto-js";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useSelector } from "react-redux";
import { RootStateI } from "@/types";
import { updateProfile } from "@/api";
import { encryptStr } from "@/lib/utils";

// 定义密码强度校验规则
const passwordStrengthSchema = z.string().refine(
  (password) => {
    const hasLowercase = /[a-z]/.test(password);
    const hasUppercase = /[A-Z]/.test(password);
    const hasNumber = /\d/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>_+=]/.test(password);

    return (
      password.length >= 8 &&
      hasLowercase &&
      hasUppercase &&
      hasNumber &&
      hasSpecialChar
    );
  },
  {
    message: "密码至少8位，并且应包含大小写、数字和特殊字符",
  }
);

const profileFormSchema = z
  .object({
    id: z.string({
      required_error: "请输入ID",
    }),
    username: z.string({
      required_error: "请输入用户名",
    }),
    oldPassword: z.string().min(8, {
      message: "请输入原密码",
    }),
    password: passwordStrengthSchema,
    passwordAgain: z.string().optional(),
  })
  .refine((data) => data.password === data.passwordAgain, {
    message: "两次密码必须一致",
    path: ["passwordAgain"],
  });

type ProfileFormValues = z.infer<typeof profileFormSchema>;

// This can come from your database or API.

export default function ProfileForm() {
  const user = useSelector((state: RootStateI) => state.user);
  const { toast } = useToast();

  const defaultValues: Partial<ProfileFormValues> = {
    id: user.id,
    username: user.username,
    oldPassword: "",
    password: "",
    passwordAgain: "",
  };

  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(profileFormSchema),
    defaultValues,
    mode: "onChange",
  });

  function onSubmit(data: ProfileFormValues) {
    if (data.username) {
      data.username = encryptStr(data.username);
    }
    if (data.oldPassword) {
      data.oldPassword = encryptStr(data.oldPassword);
    }
    if (data.password) {
      data.password = encryptStr(data.password);
    }
    if (data.passwordAgain) {
      data.passwordAgain = encryptStr(data.passwordAgain);
    }

    console.log(data);
    updateProfile(data)
      .then((res) => {
        console.log(res);
        toast({
          variant: "success",
          title: "更新成功",
        });
      })
      .catch((err) => {
        console.log(err);
        toast({
          variant: "destructive",
          title: "请求失败",
          description: `${err.detail}`,
        });
      });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <FormField
          control={form.control}
          name="id"
          render={({ field }) => (
            <FormItem>
              <div className="flex items-center justify-between">
                <FormLabel>ID</FormLabel>
              </div>
              <FormControl>
                <Input disabled={true} placeholder="ID" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="username"
          render={({ field }) => (
            <FormItem>
              <div className="flex items-center justify-between">
                <FormLabel>用户名</FormLabel>
              </div>
              <FormControl>
                <Input disabled={true} placeholder="用户名" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="oldPassword"
          render={({ field }) => (
            <FormItem>
              <div className="flex items-center justify-between">
                <FormLabel>原密码</FormLabel>
              </div>
              <FormControl>
                <PasswordInput placeholder="原密码" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <div className="flex items-center justify-between">
                <FormLabel>密码</FormLabel>
              </div>
              <FormControl>
                <PasswordInput placeholder="密码" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="passwordAgain"
          render={({ field }) => (
            <FormItem>
              <div className="flex items-center justify-between">
                <FormLabel>密码确认</FormLabel>
              </div>
              <FormControl>
                <PasswordInput placeholder="密码确认" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit">更新</Button>
      </form>
    </Form>
  );
}
